package com.ibuonline.b2b.common.importer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import com.dimeng.common.util.DBUtil;
import com.dimeng.common.util.StringUtil;
import com.ibuonline.b2b.common.ServiceFactory;
import com.ibuonline.b2b.entity.ShopAlbum;
import com.ibuonline.b2b.shop.service.ShopAlbumService;

/**
 * import album info from sqlserver to oracle
 * @author fengyong
 */
public class AlbumImport {
	
	private final static String SELECT_ALBUM_SQL = "SELECT C_AlbumID,memId, C_CompanyID,C_PicPath, C_AlbumName,C_CreateDate, C_Describe, C_IsRecommend, C_ReOrder FROM T_Album a, T_company b where a.C_companyId= b.id";
	
	private ShopAlbumService albumService = ServiceFactory.getShopAlbumService();
	
	private Connection conn = null;
	private PreparedStatement pstm = null;
	private ResultSet rs = null;
	
	public void importAlbum() {
		try {
			conn = DBUtil.getConnection();
			pstm = conn.prepareStatement(SELECT_ALBUM_SQL);
			rs = pstm.executeQuery();
			while(rs.next()) {
				ShopAlbum sa = new ShopAlbum();
				String companyId = rs.getString("memId").trim();
				String albumName = rs.getString("C_AlbumName").trim();
				String coverPic = rs.getString("C_PicPath").trim();
				String albumDesc = rs.getString("C_Describe").trim();
				Timestamp createTime = rs.getTimestamp("C_CreateDate");
				String recommended = rs.getString("C_IsRecommend").trim();
				String orderNo = rs.getString("C_ReOrder").trim();
				Timestamp lastupdate = new Timestamp(System.currentTimeMillis());
				
				List<ShopAlbum> shopAlbums = albumService.getByParams(new String[]{"companyId", "name"}, new Object[]{companyId, albumName});
				if(shopAlbums.size() > 0) {
					continue;
				}
				
				System.out.println(companyId + "---------");
				sa.setCompanyId((companyId == null | "".equals(companyId)) ? null : new Integer(companyId));
				sa.setName(albumName);
				if("1".equals(recommended)) {
					sa.setDisplay(true);
				} else {
					sa.setDisplay(false);
				}
				sa.setCover(coverPic);
				if(StringUtil.notEmpty(albumDesc)) {
					if(albumDesc.length() > 100) {
						albumDesc =  albumDesc.substring(0, 100);
					}
				}
				sa.setDescr(albumDesc);
				sa.setDisplayOrder((orderNo == null | "".equals(orderNo)) ? null : new Integer(orderNo));
				sa.setCreateTime(createTime);
				sa.setLastupdate(lastupdate);
				
				albumService.save(sa);
				
				System.out.println(sa.getId());
				
				OldIdAndNewIdMap.abumIdMap.put(rs.getString("C_AlbumID"), sa.getId());
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(conn, pstm, rs);
		}
	}
}
